/*
 * SrcFileModifier.java
 *
 *  created: 5.9.2011
 *  charset: UTF-8
 *  license: MIT (X11) (See LICENSE file for full license)
 */
package cz.mp.k3bg.core;

import cz.mp.k3bg.Application;
import static cz.mp.k3bg.Application.EOL;
import cz.mp.k3bg.log.LoggerManager;
import cz.mp.util.FileUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * {@code SrcFileModifier} vytvoří upravenou kopii zadaného HTML souboru,
 * tak aby bylo např. možno vygenerovat obsah.
 * 
 * @author Martin Pokorný
 * @version 0.1
 */
public class SrcFileModifier {
    
    private static final boolean DEBUG = false;
    private static final Logger logger =
            LoggerManager.getLogger(SrcFileModifier.class, DEBUG);
    
    private HtmlFile srcFile;
            
    private HtmlFile dstFile;
    
    /** 
     * Přidat před tagy {@code H} kotvu tagy {@literal <A name="...">}. 
     * Slouží potřebám generování obsahu.
     */
    private boolean anchorsToChapters = true;
    
    /**
     * První odstavec po nadpisu bez odsazení.
     */
    private boolean firstParagraphNoIndent = true;
    
    /**
     * Prázdné řádky (tag {@literal <br>} nebo {@literal <br />}) mezi
     * odstavci za odstavec s rozšířeným horním okrajem.
     */
    private boolean separatedParagraphs = true;
    
    private String styleName = BookFiles.DEFAULT_STYLE_FILENAME;

    
    // -----
    
    /**
     * 
     * @param srcFile
     * @param dstFile 
     */
    public SrcFileModifier(HtmlFile srcFile, HtmlFile dstFile) {
        if (srcFile==null) {
            throw new IllegalArgumentException("srcFile=null");
        }
        logger.config("srcFile = " + srcFile);
        this.srcFile = srcFile;
        
        if (dstFile==null) {
            throw new IllegalArgumentException("dstFile=null");
        }
        logger.config("dstFile = " + dstFile);
        this.dstFile = dstFile;

        if (srcFile.getAbsolutePath().equals(dstFile.getAbsolutePath())) {
            logger.warning("dstFile = srcFile");
            throw new IllegalArgumentException("dstFile = srcFile !");
        }
    }

    
    /**
     * 
     * @return 
     */
    public boolean isAnchorsToChapters() {
        return anchorsToChapters;
    }

    /**
     * 
     * @param anchorsToChapters 
     */
    public void setAnchorsToChapters(boolean anchorsToChapters) {
        logger.config("anchorsToChapters = " + anchorsToChapters);
        this.anchorsToChapters = anchorsToChapters;
    }

    /**
     * 
     * @return 
     */
    public boolean isFirstParagraphNoIndent() {
        return firstParagraphNoIndent;
    }

    /**
     * 
     * @param firstParagraphNoIndent 
     */
    public void setFirstParagraphNoIndent(boolean firstParagraphNoIndent) {
        logger.config("firstParagraphNoIndent = " + firstParagraphNoIndent);
        this.firstParagraphNoIndent = firstParagraphNoIndent;
    }

    /**
     * 
     * @return 
     */
    public boolean isSeparatedParagraphs() {
        return separatedParagraphs;
    }

    /**
     * 
     * @param separatedParagraphs 
     */
    public void setSeparatedParagraphs(boolean separatedParagraphs) {
        logger.config("separatedParagraphs = " + separatedParagraphs);
        this.separatedParagraphs = separatedParagraphs;
    }

    /**
     * 
     * @throws FileNotFoundException
     * @throws IOException 
     */
    public void modify() throws IOException {
        logger.info("");

        // vždy "UTF-8"
        dstFile.setCharsetName(Application.PREFERRED_CHARSET);

        BufferedWriter writer = dstFile.getBufferedWriter();        
                
        String result = srcFile.readFileToString();
        
        logger.fine("force Utf8 - modify in meta tags");

        if (srcFile.getMimeType() == MimeType.XHTML) {
            // příklad:
            //<?xml version="1.0" encoding="cp1250"?>
            result = result.replaceFirst(
                    "<?xml(\\s*.*\\s*)encoding=\"([^\"]*)\"?>",
                    "<?xml$1encoding=\"utf-8\"?>");
        }
        // příklady:
        //<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        //<meta http-equiv="Content-Type" content="text/html; charset=windows-1250">
        //<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
        //<meta http-equiv="Content-Type" content="text/html; charset=windows-1250" />
        //<meta http-equiv="content-type" content="text/html; charset=iso-8859-2" />
        result = result.replaceFirst(
                "<meta(\\s*.*\\s*)[Cc]ontent=\"text/html;\\s*[Cc]harset=([^\"]*)\"",
                "<meta$1content=\"text/html; charset=UTF-8\"");

        if (firstParagraphNoIndent) {
            logger.fine("firstParagraphNoIndent");
            result = result.replaceAll(
                    "(</h[123456]>)(\\s*)<p>", 
                    "$1$2<p class=\"" 
                        + StyleClassNames.NO_INDENT.getRealName() 
                        + "\">");
        }
        if (separatedParagraphs) {
            logger.fine("separatedParagraphs");
            result = result.replaceAll(
                    "<br\\s?/?>\\s*<p>|<p>\\s*</p>\\s*<p>",
                    "<br>\n<p>");
//                    "<p class=\""
//                        + StyleClassNames.WITH_TOP_MARGIN.getRealName()
//                        + "\">");
        }
        
//        if (srcFile.isInitialized()
//                && (alwaysAppendDefaultStylesheet ||
//                    (minOneStylesheet
//                    && srcFile.getStyleFiles().isEmpty())) ) {
        if (srcFile.isInitialized() //&& alwaysAppendDefaultStylesheet
                && !result.contains("href=\"" + styleName + "\"")) {
            logger.fine("add stylesheet href");
            StringBuilder sb = new StringBuilder();
            sb.append("<link rel=\"stylesheet\" ")
                    .append("href=\"")
                    .append(styleName).append("\" ")
                    .append("type=\"text/css\" />")
                    .append(EOL);
            Pattern pattern = Pattern.compile("</head>",                     
                    Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(result);
            result = matcher.replaceFirst(sb.toString() + "</head>");

            // + vytvořit ten výchozí styl
            StyleGenerator.generateDefault(
                    FileUtils.getFileDirPath(dstFile.getAbsolutePath()));
        }
        
        if (anchorsToChapters) {
            logger.fine("anchorsToChapters");
            
            BufferedReader br = new BufferedReader(new StringReader(result));
            AnchorToChapterTagger aToH = new AnchorToChapterTagger(br, writer);
            
            aToH.process();
        }
        else {
            writer.write(result);
            writer.flush();
            writer.close();            
        }
        logger.fine("(finished!)");
    }

    
}   // SrcFileModifier.java

